package com.lanzhou.yuanfen.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lanzhou.yuanfen.config.SystemConstant;
import com.lanzhou.yuanfen.exception.RollBackException;
import com.lanzhou.yuanfen.sys.entity.SocialUser;
import com.lanzhou.yuanfen.sys.entity.User;
import com.lanzhou.yuanfen.sys.entity.UserRole;
import com.lanzhou.yuanfen.sys.mapper.SocialUserMapper;
import com.lanzhou.yuanfen.sys.mapper.UserMapper;
import com.lanzhou.yuanfen.sys.mapper.UserRoleMapper;
import com.lanzhou.yuanfen.sys.service.IUserService;
import com.lanzhou.yuanfen.util.PlusHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lcllge
 * @since 2019-12-02
 */
@Service
@Transactional(propagation = Propagation.NESTED, isolation = Isolation.DEFAULT, rollbackFor = RollBackException.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private SocialUserMapper socialUserMapper;
    @Resource
    private UserRoleMapper userRoleMapper;

    /**
     * 获取用户信息
     *
     * @param openId
     * @return
     */
    @Transactional(readOnly = true, rollbackFor = RollBackException.class)
    @Override
    public User getUserByOpenId(String openId) {
        return userMapper.selectUserByOpenId(openId);
    }


    @Override
    public void registerFillUser(User user, String openId) {
        int save = userMapper.insert(user);
        if (save < 1) {
            throw new RollBackException("完善用户信息失败, 请稍后再试");
        }
        // 数据库有无用户判断是否需要完善用户信息
        SocialUser socialUser = socialUserMapper.selectOne(new QueryWrapper<SocialUser>()
                .eq("open_id", openId));
        // 添加用户
        int save1 = userRoleMapper.insert(new UserRole(user.getUserKey(), SystemConstant.DEFAULT_ROLE));
        SocialUser setUserKey = new SocialUser().setSocialKey(socialUser.getSocialKey())
                .setUserKey(user.getUserKey());
        String regionAddr = getRegionAddr(socialUser);
        User user1 = new User().setUserKey(user.getUserKey())
                .setAvatar(socialUser.getAvatar())
                .setSourceRegion(regionAddr)
                .setGender(socialUser.getGender())
                .setWink(0)
                .setFocus(0)
                .setGrade(socialUser.getGrade());
        if (StringUtils.isEmpty(socialUser.getAvatar())) {
            if ("男".equals(socialUser.getGender())) {
                user1.setAvatar("/bootstrap/images/open/anonymous_women.jpg");
            } else if ("女".equals(socialUser.getGender())) {
                user1.setAvatar("/bootstrap/images/open/anonymous_men.jpg");
            } else {
                user1.setAvatar("/bootstrap/images/open/anonymous_secret.jpg");
            }
        }
        if (save1 < 1) {
            throw new RollBackException("完善用户信息失败, 请稍后再试");
        }
        int save3 = userMapper.updateById(user1);
        int save2 = socialUserMapper.updateById(setUserKey);
        if (save2 < 1 || save3 < 1) {
            throw new RollBackException("完善用户信息失败, 请稍后再试");
        }
    }

    /**
     * 获取来源归属地
     *
     * @param socialUser
     * @return
     */
    private String getRegionAddr(SocialUser socialUser) {
        String region = "";
        if (!StringUtils.isEmpty(socialUser.getProvince())) {
            region += socialUser.getProvince() + "省";
        }
        if (!StringUtils.isEmpty(socialUser.getCity())) {
            region += socialUser.getCity() + "市";
        }
        return region;
    }

    /**
     * 注册用户给默认角色
     *
     * @param user
     */
    @Override
    public void registerUser(User user) {
        user.setAvatar("/bootstrap/images/open/anonymous_secret.jpg");
        int save1 = userMapper.insert(user);
        if (save1 < 1) {
            throw new RollBackException("注册新用户失败, 请稍后再试");
        }
        UserRole userRole = new UserRole().setUserKey(user.getUserKey())
                .setRoleKey(SystemConstant.DEFAULT_ROLE);
        int save2 = userRoleMapper.updateById(userRole);
        if (save2 < 1) {
            throw new RollBackException("注册新用户失败, 请稍后再试");
        }
    }

    /**
     * 新增或修改
     *
     * @param user
     */
    @Override
    public void insertOrModify(User user) {
        List<UserRole> addUR = null;
        String roles = user.getRoles();
        String[] split = roles.split(",");
        Set<Long> addRole = getRoleKey(split);
        Set<Long> afterCopy = getRoleKey(split);
        Long userKey = user.getUserKey();
        if (userKey != null) {
            List<UserRole> userRoleList = userRoleMapper.selectList(new QueryWrapper<UserRole>()
                    .eq("user_key", userKey));
            if (userRoleList.size() == 0) {
                addUR = obtainRole(addRole, userKey);
                PlusHelper.saveBatch(addUR);
            } else {
                Set<Long> remove = userRoleList.stream().map(UserRole::getRoleKey).collect(Collectors.toSet());
                // 只需要新增的(原来有的删了)
                addRole.removeIf(remove::contains);
                remove.removeIf(afterCopy::contains);
                addUR = obtainRole(addRole, userKey);
                PlusHelper.saveBatch(addUR);
                userRoleMapper.delete(new UpdateWrapper<UserRole>().eq("user_key", userKey).in(remove.size() > 0, "role_key", remove));
            }
            userMapper.updateById(user);
        } else {
            userMapper.insert(user);
            userKey = user.getUserKey();
            addUR = obtainRole(addRole, userKey);
            PlusHelper.saveBatch(addUR);
        }
    }

    @Override
    public void removeUser(String userKey) {
        userRoleMapper.delete(new UpdateWrapper<UserRole>().eq("user_key", userKey));
        userMapper.deleteById(userKey);
    }

    /**
     * 用于直接修改原来没有和新增
     *
     * @param roles
     * @param userKey
     * @return
     */
    private List<UserRole> obtainRole(Set<Long> roles, Long userKey) {
        List<UserRole> urList = new ArrayList<>();
        for (Long ur : roles) {
            UserRole userRole = new UserRole();
            userRole.setUserKey(userKey).setRoleKey(ur);
            urList.add(userRole);
        }
        return urList;
    }

    /**
     * 用于获取角色ID组数据
     *
     * @param split
     * @return
     */
    private Set<Long> getRoleKey(String[] split) {
        Set<Long> result = new HashSet<>();
        for (String s : split) {
            if (!"".equals(s)) {
                result.add(Long.valueOf(s));
            }
        }
        return result;
    }

}
